package cn.seapon.talker.db;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import cn.seapon.talker.bean.Account;
import cn.seapon.talker.bean.MessageEntity;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

/**
 * @author 作者 E-mail:
 * @version 创建时间：2015年1月8日 下午10:39:17 类说明
 */
public class TalkerOrmliteHelper extends OrmLiteSqliteOpenHelper {
	private static final String DB_NAME = "ormlite.db";
	private static final int DB_VERSION = 1;
	private Context context;

	// 对应着accounts表
	private Dao<Account, Integer> accountsDao;
	//对应msg表
	private Dao<MessageEntity, Integer> messageEntityDao;

	private static TalkerOrmliteHelper instance;

	private TalkerOrmliteHelper(Context context) {
		super(context, DB_NAME, null, DB_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase arg0, ConnectionSource arg1) {
		try {
			//创建表
			TableUtils.createTable(connectionSource, Account.class);
			TableUtils.createTable(connectionSource, MessageEntity.class);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, ConnectionSource arg1, int arg2,
			int arg3) {
		try {
			//删除表
			TableUtils.dropTable(connectionSource, Account.class, true);
			TableUtils.dropTable(connectionSource, MessageEntity.class, true);
			//重新创建
			onCreate(arg0, connectionSource);
		} catch (SQLException e) {
			e.printStackTrace();
		} 
	}

	/**
	 * 获取自身实例
	 * 
	 * @param context
	 * @return
	 */
	public static synchronized TalkerOrmliteHelper getHelper(Context context) {
		if (instance == null) {
			instance = new TalkerOrmliteHelper(context);
		}
		return instance;
	}

	public Dao<Account, Integer> getAccountsDao() throws SQLException {
		if (accountsDao == null) {
			accountsDao = getDao(Account.class);	
		}
		return accountsDao;
	}
	
	public Dao<MessageEntity, Integer> getMessageEntityDao() throws SQLException{
		if (messageEntityDao == null) {
			messageEntityDao = getDao(MessageEntity.class);	
		}
		return messageEntityDao;		
	}

	/**
	 * 释放资源
	 */
	@Override
	public void close() {
		super.close();
        accountsDao = null;  
	}
	

}
